package server;

import gms.GMSManager;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.PropertyConfigurator;

import config.Configure;

import network.MessageService;

public class WeiboCacheServer {
	public static void initLog4j() {
		if (System.getProperty("log4j.defaultInitOverride", "true")
				.equalsIgnoreCase("true")) {
			String config = System.getProperty("log4j_configuration",
					"log4j-server.properties");
			URL configLocation = null;
			try {
				// try loading from a physical location first.
				configLocation = new URL(config);
				System.out.println("config:" + config);
			} catch (MalformedURLException ex) {
				// then try loading from the classpath.
				configLocation = WeiboCacheServer.class.getClassLoader()
						.getResource(config);
			}

			if (configLocation == null)
				throw new RuntimeException(
						"Couldn't figure out log4j configuration: " + config);

			// Now convert URL to a filename
			String configFileName = null;
			try {
				// first try URL.getFile() which works for opaque URLs
				// (file:foo) and paths without spaces
				configFileName = configLocation.getFile();
				File configFile = new File(configFileName);
				// then try alternative approach which works for all
				// hierarchical URLs with or without spaces
				if (!configFile.exists())
					configFileName = new File(configLocation.toURI())
							.getCanonicalPath();
			} catch (Exception e) {
				throw new RuntimeException(
						"Couldn't convert log4j configuration location to a valid file:" + configLocation,
						e);
			}

			PropertyConfigurator.configureAndWatch(configFileName, 10000);
			org.apache.log4j.Logger.getLogger(WeiboCacheServer.class).info(
					"Logging initialized");
		}
	}

	public void start() {
		Configure.init("./conf/server.yaml");
		GMSManager.getInstance().Init();
		MessageService.instance().initServer();
		RpcServer.instance().initServer();
	}

	public static void main(String[] args) {
		WeiboCacheServer.initLog4j();
		WeiboCacheServer server = new WeiboCacheServer();
		server.start();
	}
}
